import "./reset.css";
import { handleTree } from "@/utils/agentServerTree";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { type Ref, ref, computed, reactive, onMounted } from "vue";
import { getAccount } from "@/utils/auth";
import { PlusColumn } from "plus-pro-components";
import { agentSettingType } from "@/utils/commonType";
import {
  createAppAgentConfContext,
  createServerAgentConfContext,
  getAgentServerTreeData,
  getAgentSettingList,
  saveAgentSetting
} from "@/api/agent";
import { ElMessageBox } from "element-plus";

export function useLogSetting(tableRef: Ref, treeRef: Ref) {
  const dataList = ref([]);
  const curNodeName = ref();
  const loading = ref(true);
  const roleInfo = getAccount().accountType;
  const curTenantId = getAccount().tenantId;

  const settingVisible = ref(false);
  const canAdd = ref(true);
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const settingInfo = reactive<agentSettingType>({
    pid: "",
    belongId: "",
    belongType: "",
    optionItem: "",
    optionDesc: "",
    optionValue: "",
    settingDesc: "",
    section: ""
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 80]
  });
  const columns: PlusColumn[] = [
    {
      label: "配置项",
      width: 160,
      prop: "optionItem",
      valueType: "text"
    },
    {
      label: "配置说明",
      width: 160,
      prop: "optionDesc",
      valueType: "text"
    },
    {
      label: "配置值",
      width: 160,
      prop: "optionValue",
      valueType: "copy"
    },
    {
      label: "值说明",
      width: 160,
      prop: "settingDesc",
      valueType: "textarea"
    }
  ];

  const tableColumns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 60
    },
    {
      label: "配置项",
      prop: "optionItem",
      width: 180
    },
    {
      label: "配置项说明",
      prop: "optionDesc",
      width: 180,
      showOverflowTooltip: true
    },
    {
      label: "配置值",
      prop: "optionValue",
      width: 280
    },
    {
      label: "配置值说明",
      prop: "settingDesc",
      showOverflowTooltip: true
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  function handleUpdate(row) {
    console.log(row);
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    if (curClickDId.value === "root") {
      curClickDId.value = "";
    }
    let section = "";

    let params = {};
    if (curClickType.value === "cloud") {
      params = {
        ...pagination,
        belongType: "server",
        belongId: curClickDId.value
      };
      section = "server";
    } else if (curClickType.value === "server") {
      params = {
        ...pagination,
        belongType: "server",
        belongId: curClickDId.value
      };
      section = "location";
    } else {
      section = "";
      dataList.value = null;
      pagination.currentPage = 0;
      pagination.total = 0;
    }
    if (section != "") {
      getAgentSettingList(section, params)
        .then(result => {
          dataList.value = result.data.list;
          pagination.total = result.data.total;
          pagination.pageSize = result.data.pageSize;
          pagination.currentPage = result.data.currentPage;
        })
        .catch(err => {
          message(`加载服务配置清单异常：${err.message}`, {
            type: "error"
          });
        });
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    treeRef.value.onTreeReset();
    onSearch();
  };
  const curClickDId = ref();
  const curClickType = ref();
  function onTreeSelect({ pid, selected, nodeType, nodeName }) {
    if (nodeType == "cloud") {
      curNodeName.value = "【服务云】" + nodeName + "-代理配置清单";
      canAdd.value = false;
    } else if (nodeType == "server") {
      curNodeName.value = "【应用】" + nodeName + "-代理配置清单";
      canAdd.value = false;
    } else {
      curNodeName.value = "代理配置清单";
      canAdd.value = true;
    }
    const vpid = selected ? pid : "";
    curClickDId.value = vpid;
    curClickType.value = nodeType;
    onSearch();
  }

  function openDialog(row?: agentSettingType) {
    settingVisible.value = true;

    settingInfo.optionItem = row.optionItem;
    settingInfo.pid = row.pid;
    settingInfo.belongId = curClickDId.value;
    settingInfo.belongType = "server";
    settingInfo.optionDesc = row.optionDesc;
    settingInfo.optionValue = row.optionValue;
    settingInfo.section = row.section;
    settingInfo.settingDesc = row.settingDesc;
  }

  function createAgentConf(){
    ElMessageBox.confirm(`确认要重新生成代理配置?`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    })
      .then(async () => {
        if(curClickType.value=="cloud"){
          createServerAgentConfContext(curClickDId.value)
          .then(result => {
            message(`服务云代理配置内容生成成功：${result.data}`, {
              type: "success"
            });
          })
          .catch(err => {
            message(`服务云代理配置内容生成失败：${err.message}`, {
              type: "error"
            });
          });
        }else if(curClickType.value=="server"){
          createAppAgentConfContext(curClickDId.value)
          .then(result => {
            message(`应用代理配置内容生成成功：${result.data}`, {
              type: "success"
            });
          })
          .catch(err => {
            message(`应用代理配置内容生成失败：${err.message}`, {
              type: "error"
            });
          });
        }
        
      })
      .catch(() => {});
  }
  function handleSaveSetting() {
    console.log(settingInfo.optionValue);
    saveAgentSetting(settingInfo)
      .then(result => {
        message(`更新日志采集配置成功`, {
          type: "success"
        });
        onSearch();
        settingVisible.value = false;
      })
      .catch(err => {
        message(`更新日志采集配置异常：${err.message}`, {
          type: "error"
        });
      });
  }

  onMounted(async () => {
    treeLoading.value = true;
    onSearch();

    // 应用树
    let tenantId = "";
    if (roleInfo != 1) {
      tenantId = curTenantId;
    }
    getAgentServerTreeData(0, tenantId)
      .then(data => {
        higherDeptOptions.value = handleTree(data.data);
        treeData.value = handleTree(data.data);
      })
      .catch(err => {
        message(`获取应用清单异常：${err.message}`, {
          type: "error"
        });
      });
    treeLoading.value = false;
  });

  return {
    loading,
    tableColumns,
    curNodeName,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleSizeChange,
    handleCurrentChange,
    settingVisible,
    columns,
    settingInfo,
    canAdd,
    handleSaveSetting,
    createAgentConf
  };
}
